<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    pageContext.setAttribute("App_Path", request.getContextPath());
%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <title>HRSystem</title>

    <!-- Bootstrap -->
    <link href="${App_Path}/static/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="${App_Path}/static/css/style.css" rel="stylesheet">

    <link href="${App_Path}/static/dist/css/bootstrap-select.min.css" rel="stylesheet">
</head>
<body>
<!-- Fixed navbar -->
<nav class="navbar navbar-default navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
                    aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="${App_Path}">人力资源管理系统</a>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
            <ul class="nav navbar-nav">
                <li class=""><a href="${App_Path}">首页</a></li>
                <li class="dropdown active">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                       aria-expanded="false">员工管理 <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="${App_Path}/list">查看员工信息</a></li>
                        <li><a href="${App_Path}/input">新增员工信息</a></li>
                    </ul>
                </li>
            </ul>
        </div><!--/.nav-collapse -->
    </div>
</nav>

<!-- Begin page content -->
<div class="container">
    <div class="page-header">
        <h3>查看员工信息</h3>
    </div>
    <form action="#" method="post" class="" id="emp-form">
        <div class="operation btn-right">
            <a href="${App_Path}/chart">
                <button type="button" class="btn btn-primary"><span class="glyphicon glyphicon-signal"
                                                                    aria-hidden="true"></span> 查看员工分布
                </button>
            </a>
            <a href="${App_Path}/export">
                <button type="button" class="btn btn-primary"><span class="glyphicon glyphicon-save"
                                                                    aria-hidden="true"></span> 导出数据
                </button>
            </a>
            <%--            <a href="${App_Path}/input">--%>
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal"><span
                    class="glyphicon glyphicon-plus"
                    aria-hidden="true"></span> 新 增
            </button>
            <%--            </a>--%>

            <button type="button" class="btn btn-danger" id="emp_delete_all"><span class="glyphicon glyphicon-remove"
                                                                                   aria-hidden="true"></span> 批量删除
            </button>
        </div>
        <table class="table table-striped table-hover list-table" id="emps-table">
            <thead>
            <tr>
                <th><input type="checkbox" id="check_all"></th>
                <th>ID</th>
                <th>姓名</th>
                <th>性别</th>
                <th>Email</th>
                <th>部门</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>

            </tbody>
            <tfoot>

            </tfoot>

        </table>
    </form>
    <input type="hidden" id="pn" value="${requestScope.pn}">
    <div id="pageIn"></div>
    <div id="pageT"></div>
</div>
<footer class="footer">
    <div class="container">
        <p class="text-muted">CC 2020杭州职业技术学院 软件技术专业</p>
    </div>
</footer>
<!-- 模态框（Modal） -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    新增员工信息
                </h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" role="form">
                    <div class="form-group">
                        <label for="empName" class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="empName" id="empName" placeholder="Name">
                            <span class="help-block"> </span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="" class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="empGender" value="1"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="empGender" value="0"> 女
                            </label>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="empEmail" class="col-sm-2 control-label">Email</label>
                        <div class="col-sm-10">
                            <input type="email" class="form-control" name="empEmail" id="empEmail" placeholder="Email"
                                   value="">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="" class="col-sm-2 control-label">部门</label>
                        <div class="col-sm-10">
                            <select id="sel" class="form-control selectpicker" title="请选择部门" name="deptId"></select>
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <button type="button" id="emp_save_btn" class="btn btn-primary col-xs-12 col-md-12">保存</button>
                </form>
            </div>
            <div class="modal-footer">
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->


    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery，所以必须放在前边) -->
    <script src="${App_Path}/static/js/jquery.min.js"></script>
    <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
    <script src="${App_Path}/static/dist/js/bootstrap.min.js"></script>

    <script src="${App_Path}/static/js/bootstrap-select.min.js"></script>
    <script type="text/javascript">
        var currPage = $("#pn").val();
        $(function () {
            to_page(currPage);
        });

        function to_page(pn) {
            //发送获取员工信息的异步请求
            $.ajax({
                url: "${App_Path}/emps",
                data: {"pn": pn},
                type: "GET",
                dataType: "json",
                success: function (result) {
                    if (result.code == 100) {
                        //操作成功
                        if (result.extend.pageInfo.list.length > 0) {
                            //解析数据,显示员工信息
                            build_emp_table(result);
                            //解析数据，显示分页信息
                            build_page_nav(result);
                        } else {
                            $("#emps-table tbody").empty();
                            $("#emps-table tfoot").empty();
                            $("#emps-table tbody").append("<tr><td colspan='7'>没有任何员工信息!!!</td></tr>");
                        }
                    } else {
                        //操作失败
                        $("#emps-table tbody").empty();
                        $("#emps-table tfoot").empty();
                        $("#emps-table tbody").append("<tr><td colspan='7'>操作失败，请稍后再试!</td></tr>");
                    }
                    // console.log(result)
                },
                error: function () {
                    //请求过程出错的处理
                    $("#emps-table tbody").empty();
                    $("#emps-table tfoot").empty();
                    $("#emps-table tbody").append("<tr><td colspan='7'>请求出错，请稍后再试!</td></tr>")
                }
            });
            // 请求成功后，显示员工信息及分页信息
        }

        function build_emp_table(result) {
            $("#emps-table tbody").empty();
            var emps = result.extend.pageInfo.list;
            $.each(emps, function (index, emp) {

                var chkTd = $("<td></td>").append($("<input>").attr("type", "checkbox").addClass("check-item"));
                var empIdTd = $("<td></td>").append(emp.empId);
                var empNameTd = $("<td></td>").append(emp.empName);
                var empGenderTd = $("<td></td>").append(emp.empGender == "1" ? "男" : "女");
                var empEmailTd = $("<td></td>").append(emp.empEmail);
                var empDeptTd = $("<td></td>").append(emp.department.deptName);
                var editBtn = $("<button></button>").addClass("btn btn-warning tbtn edit_btn").attr("type", "button").append($("<span></span>").addClass("glyphicon glyphicon-wrench").attr("aria-hidden", true).append("修改"));
                var deleteBtn = $("<button></button>").addClass("btn btn-danger delete-btn").attr("type", "button").append($("<span></span>").addClass("glyphicon glyphicon-remove").attr("aria-hidden", true).append("删除"));
                var empOperationTd = $("<td></td>").append(editBtn).append(deleteBtn);

                editBtn.attr({"edit-id": emp.empId, "pn": result.extend.pageInfo.pageNum});
                deleteBtn.attr("delete-id", emp.empId);

                $("<tr></tr>").append(chkTd, empIdTd, empNameTd, empGenderTd, empEmailTd, empDeptTd, empOperationTd).appendTo("#emps-table tbody");
            })
        }

        $(document).on("click", ".edit_btn", function () {
            window.location.href = "${App_Path}/edit/" + $(this).attr("edit-id") + "-" + $(this).attr("pn");
        });

        function build_page_nav(result) {
            var pageInfo = result.extend.pageInfo;
            currPage = pageInfo.pageNum;
            $("#pn").val(currPage);
            var pageInfoSpan = $("<span></span>").append("当前第" + pageInfo.pageNum + "页，总" + pageInfo.pages + "页，总" + pageInfo.total + "条记录");

            $("#pageIn").empty();
            $("#pageIn").append(pageInfoSpan);

            var nav = $("<nav></nav>").addClass("page-dev").attr("aria-label", "Page navigation");
            var ul = $("<ul></ul>").addClass("pagination");

            var homeLi = $("<li></li>").append($("<a></a>").append("首页"));
            if (pageInfo.isFirstPage) {
                homeLi.addClass("disabled");
            } else {
                homeLi.click(function () {
                    to_page(1);
                });
            }
            ul.append(homeLi);

            var preLi = $("<li></li>").append($("<a></a>").append($("<span></span>").attr("aria-hidden", true).append("&laquo;")).attr("aria-label", "Previous"));
            if (!pageInfo.hasPreviousPage) {
                preLi.addClass("disabled");
            } else {
                preLi.click(function () {
                    to_page(pageInfo.pageNum - 1);
                })
            }
            ul.append(preLi);

            $.each(pageInfo.navigatepageNums, function (index, item) {
                var pageLi = $("<li></li>").append($("<a></a>").append(item));
                if (item == pageInfo.pageNum) {
                    pageLi.addClass("active");
                }
                pageLi.click(function () {
                    to_page(item);
                })
                ul.append(pageLi);
            })

            var nextLi = $("<li></li>").append($("<a></a>").append($("<span></span>").attr("aria-hidden", true).append("&raquo;")).attr("aria-label", "Previous"));
            if (!pageInfo.hasNextPage) {
                nextLi.addClass("disabled");
            } else {
                nextLi.click(function () {
                    to_page(pageInfo.pageNum + 1);
                })
            }
            ul.append(nextLi);


            var lastLi = $("<li></li>").append($("<a></a>").append("末页"));
            if (pageInfo.isLastPage) {
                lastLi.addClass("disabled");
            } else {
                lastLi.click(function () {
                    to_page(pageInfo.pages);
                });
            }
            ul.append(lastLi);

            $("#pageT").empty();
            $("#pageT").append(nav.append(ul));
        };


        $(document).on("click", ".delete-btn", function () {
            //var empId = $(this).parents("tr").find("td:eq(1)").text();
            var empName = $(this).parents("tr").find("td:eq(2)").text();
            if (confirm("确认删除【" + empName + "】吗?")) {
                //发送异步请求,删除员工
                $.ajax({
                    url: "${App_Path}/emp/" + $(this).attr("delete-id"),
                    type: "delete",
                    dataType: "json",
                    success: function (result) {
                        alert(result.msg);
                        if (result.code == 100) {
                            //删除成功
                            //局部刷新
                            to_page(currPage);
                        }
                    }
                });
            }
        });
        $("#check_all").click(function () {
            $(".check-item").prop("checked", $(this).prop("checked"));
        });

        $(document).on("click", ".check-item", function () {
            $("#check_all").prop("checked", $(".check-item").length == $(".check-item:checked").length);
        });

        $("#emp_delete_all").click(function () {

            if ($(".check-item:checked").length == 0) {
                alert("请选择需要删除的员工！");
                return;
            }

            var empNames = "", empIds = "";
            $.each($(".check-item:checked"), function () {
                empNames = empNames + $(this).parents("tr").find("td:eq(2)").text() + ",";
                empIds = empIds + $(this).parents("tr").find("td:eq(1)").text() + "-";
            });
            empIds = empIds.substring(0, empIds.length - 1);
            empNames = empNames.substring(0, empNames.length - 1);


            if (confirm("确认删除【" + empNames + "】吗?")) {
                //发送异步请求,批量删除员工
                $.ajax({
                    url: "${App_Path}/emp/" + empIds,
                    type: "delete",
                    dataType: "json",
                    success: function (result) {
                        alert(result.msg);
                        if (result.code == 100) {
                            //删除成功
                            //局部刷新
                            $("#check_all").prop("checked", false);
                            to_page(currPage);
                        }
                    }
                });
            }
        })

        //模态框添加
        $(function () {
            //发送异步请求，获取部门信息
            $.ajax({
                url:"${App_Path}/depts",
                type:"get",
                dataType:"json",
                success:function (result) {
                    if(result.code == 100){
                        $.each(result.extend.depts,function (index,dept) {
                            var optionEle = $("<option></option>").attr("value",dept.id).append(dept.deptName);
                            $("#sel").append(optionEle);
                        });
                        $("#sel").selectpicker("refresh");
                    }
                }
            })
        });

        $("#emp_save_btn").click(function () {
            // 数据校验
            if($(this).attr("check-val")=="fail"){
                return false;
            }

            // 姓名验证
            var empName = $("#empName").val();
            var regName = /(^[a-zA-Z0-9]{6,13}$)|(^[\u4e00-\u9fa5]{2,6}$)/;
            if(regName.test(empName)){
                //验证通过
                show_validation_msg("#empName","success","");
            }else{
                //验证失败
                show_validation_msg("#empName","error","用户名必须是2-6位中文或6-13位英文数字组合");
                return false;
            }

            // 性别验证
            if($("[name='empGender']:checked").length > 0){
                show_validation_msg("[name='empGender']","success","");
            }else {
                show_validation_msg("[name='empGender']","error","请选择性别！");
                return false;
            }

            //邮箱验证
            var empEmail = $("#empEmail").val();
            var regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
            if(regEmail.test(empEmail)){
                //验证通过
                show_validation_msg("#empEmail","success","");
            }else{
                //验证失败
                show_validation_msg("#empEmail","error","只允许英文字母、数字、下划线、英文句号、以及中划线组成");
                return false;
            }

            //部门验证
            if($("[name='deptId']").val() != ""){
                //验证通过
                show_validation_msg("[name='deptId']","success","");
            }else{
                //验证失败
                show_validation_msg("[name='deptId']","error","请选择部门！");
                return false;
            }
            //发送异步请求
            $.ajax({
                url:"${App_Path}/emp",
                data:$("form").serialize(),
                type:"post",
                dataType:"json",
                success:function (result) {
                    console.log(result);
                    if(result.code == 100){
                        //保存成功
                        window.location.href="${App_Path}/list";
                    }else {
                        //校验失败或保存失败
                        if(undefined != result.extend.empName){
                            show_validation_msg("#empName","error",result.extend.empName);
                        }
                        if(undefined != result.extend.empEmail){
                            show_validation_msg("#empEmail","error",result.extend.empEmail);
                        }
                    }
                }

            })
        });

        function show_validation_msg(element,status,msg) {
            var formDiv = $(element).parents("div.form-group");
            formDiv.removeClass("has-success has-error");
            if("success" == status){
                formDiv.addClass("has-success");
            }else{
                formDiv.addClass("has-error");
            }
            formDiv.find("span.help-block").text(msg);
        }

        $("#empName").change(function () {
            $.ajax({
                url:"${App_Path}/checkName",
                data:{"empName":$(this).val()},
                type:"post",
                dataType:"json",
                success:function (result) {
                    if(result.code == 100){
                        show_validation_msg("#empName","success",result.extend.success_msg);
                        $("#emp_save_btn").attr("check-val","success");
                    }else{
                        show_validation_msg("#empName","error",result.extend.fail_msg);
                        $("#emp_save_btn").attr("check-val","fail");
                    }
                }
            });
        });
    </script>
</body>
</html>